<script setup>
import { useAdminStore } from '@/stores';
import { getTactics, getTacticsDevices } from '@/api/equipment/tactics'
import { ref, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// 项目组
import { getProject } from '@/api/equipment/tactics'
const props = defineProps({
  type: String,
  backpath: String,
})
const basicInfo = ref({})

const adminStore = useAdminStore()
const loopPeriod = ref({
  num: '',
  unit: ''
})
const unit = ref([
  { value: 'D', label: '天' },
  { value: 'W', label: '每周' },
  { value: 'M', label: '每月' },
])

//拼接周期
watch(loopPeriod, (newVal) => {
  console.log(newVal.num, newVal.unit)
  if (newVal.num && newVal.unit) {
    // console.log('监视修改loopPeriod')
    // basicInfo.value.loopPeriod = loopPeriod.value.unit.replace('N', newVal.num)
    basicInfo.value.loopPeriod = `${newVal.num}` + `${newVal.unit}`
    // console.log('basicInfo.loopPeriod', basicInfo.value.loopPeriod)
  } else {
    basicInfo.value.loopPeriod = ''
  }
}, { deep: true })
// 部门选择设置
const basicProps = ref({
  value: 'id',
  label: 'name',
  children: 'children',
  emitPath: false
})
// 生效及结束时间可选范围判定
function disableStartDate(time) {
  return time < Date.now()
}
function disableEndDate(time) {
  if (basicInfo.value.startDate) {
    return time < new Date(basicInfo.value.startDate)
  } else {
    return true
  }
}
// form规则
const basicRuls = {
  name: [{ required: true, message: '请输入策略名称', trigger: 'blur' }],
  loopPeriod: [{ required: true, message: '请输入循环周期', trigger: 'change' }],
  duration: [{ required: true, message: '请输入任务持续天数', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择使用部门', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择生效时间', trigger: 'change' }],
}

//新增设备按键 || 项目组
const projectChooseRef = ref(null)
const projectList = ref([])
const projectChoosen = ref()
const checkList = ref([])
const addDisable = ref(true)

watch(basicInfo, async (newVal) => {
  // 设备选择按键
  if (newVal.deptId) {
    addDisable.value = false
    // 修改项目组下拉框
    projectChoosen.value = null
    await getProject().then(res => {
      console.log(res)
      projectList.value = res.data.data.filter(item => item.deptId === basicInfo.value.deptId || item.deptId === null && item.type === props.type)
    })
  } else {
    addDisable.value = true
  }
}, { deep: true })

function chooseProject() {

  if (basicInfo.value.projectId) {
    checkList.value = projectList.value?.find(item => item.id === basicInfo.value.projectId)?.itemsList
  }
  console.log('checklist', checkList.value)
}

const drawVisiable = ref(false)
function addDevice() {
  drawVisiable.value = true
}

import DeviceSelect from './DeviceSelect.vue';
const deviceSelected = ref([])
const deviceListRef = ref(null)
const dialogVisiable = ref(false)
const remark = ref({
  id: '',
  remark: ''
})
function handleClick(row, cell) {
  console.log(row, cell)
  if (cell.property === 'remark') {
    remark.value.remark = row.remark
    remark.value.id = row.id
    dialogVisiable.value = true
  }
}
function remarkConfirm() {
  deviceSelected.value.find(item => item.id === remark.value.id).remark = remark.value.remark
  dialogVisiable.value = false
}
function remove(row) {
  deviceSelected.value = deviceSelected.value.filter(item => item.id !== row.id)
}
// 项目组


//页面提交或取消
import { addTactics, updateTactics } from '@/api/equipment/tactics'
// import { Tactics_type } from '@/constants/equipment'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
// import { Tactics_type } from '@/constants/equipment';
const router = useRouter()
const basicFormRef = ref(null)
watch(deviceSelected, (newVal) => {
  basicInfo.value.devicelist = newVal.map(item => { return { deviceId: item.id, status: item.status, remark: item.remark } })
}, { deep: true })
async function submitTactics() {

  // type prop传递
  basicInfo.value.type = props.type
  // basicInfo.value.projectId = projectChoosen.value
  if (route.params.id === 'new') {
    await basicFormRef.value.validate(async (valid) => {
      if (valid) {
        console.log(basicInfo.value)
        await addTactics('add:', basicInfo.value).then(res => {
          if (res.data.success) {
            ElMessage.success(res.data.data)
            router.push(props.backpath)
          }
        })
      }
    })
  } else {
    await basicFormRef.value.validate(async (valid) => {
      if (valid) {
        console.log('update:', basicInfo.value)
        await updateTactics(basicInfo.value).then(res => {
          if (res.data.success) {
            ElMessage.success(res.data.data)
            router.push(props.backpath)
          }
        })
      }
    })
  }

}
function cancelTactics() {
  basicFormRef.value.resetFields()
  router.push(props.backpath)
}

//如果有路径参数ID，进行处理
if (route.params.id !== 'new') {
  console.log(route.params.id)
  nextTick(async () => {
    await getTactics({ id: route.params.id }, props.type).then(res => {
      console.log('record0', res.data.data.records[0])
      basicInfo.value = res.data.data.records[0]
      console.log('basicinfo', basicInfo.value)
      loopPeriod.value.unit = basicInfo.value.loopPeriod.at(-1)
    })
    await getTacticsDevices(route.params.id).then(res => {
      console.log('devices', res)
      deviceSelected.value = res.data.data.map(item => {
        return { deviceId: item.deviceId, id: item.deviceId, name: item.deviceName, code: item.deviceCode, status: item.status, remark: item.remark }
      })
      // deviceSelected.value = res.data.data
    })
    // projectChoosen.value = basicInfo.value.projectId
    await getProject().then(res => {
      console.log('projectlist', res)
      projectList.value = res.data.data.filter(item => item.deptId === basicInfo.value.deptId || item.deptId === null && item.type === props.type)
    })
    chooseProject()
    console.log(basicInfo.value.projectId)
  })

}
</script>

<template>
  <el-text tag="b" size="large">基本信息 </el-text>
  <el-row>
    <el-form :inline="true" class="basicInfo" :model="basicInfo" :rules="basicRuls" ref="basicFormRef" size="small">
      <el-form-item label="策略名称" prop="name">
        <el-input v-model="basicInfo.name"></el-input>
      </el-form-item>
      <el-tooltip :content="tooltipLoop" placement="top" effect="light">
        <template #content>
          “天”指每几天触发一次。<br>
          “每周”指每周几触发该任务。<br>
          “每月”指每月几号触发该任务。
        </template>
        <el-form-item label="循环周期" prop="loopPeriod">
          <el-input-number :step="1" step-strictly :min="1" :max="31" size="small" style="width: 90px;" placeholder="周期"
            v-model="loopPeriod.num"></el-input-number>
          <el-select placeholder="单位" v-model="loopPeriod.unit">
            <el-option v-for="(item, index) in unit" :key="index" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
      </el-tooltip>
      <el-form-item label="任务持续天数" prop="duration">
        <el-input-number v-model="basicInfo.duration" :step="1" step-strictly :min="1" size="small"
          style="width: 90px;"></el-input-number>
      </el-form-item>
      <el-form-item label="使用部门" prop="deptId">
        <el-cascader class="dept" v-model="basicInfo.deptId" :options="adminStore.deptList"
          :props="basicProps"></el-cascader>
      </el-form-item>
      <el-form-item label="生效时间" prop="startDate">
        <el-date-picker type="date" v-model="basicInfo.startDate" :disabled-date="disableStartDate"
          value-format="YYYY-MM-DD" style="width: 150px;"></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker type="date" v-model="basicInfo.endDate" :disabled-date="disableEndDate"
          value-format="YYYY-MM-DD" style="width: 150px;"></el-date-picker>
      </el-form-item>
    </el-form>
  </el-row>
  <div style="max-width: 100%; margin-bottom: 8px;">
    <el-alert title="策略说明" type="success">
      <template #default>
        <div>1. 结束时间不填写，则任务不间断自动生成。</div>
        <div>2. 若不选择设备，不会生成任务。</div>
      </template>
    </el-alert>
  </div>
  <el-text tag="b" size="large">应用设备 </el-text>
  <el-button type="primary" size="small" style="margin-left: 50px; width: 84px;" @click="addDevice"
    :disabled="addDisable">新增设备</el-button>
  <!-- <el-button type="danger" size="small" style="margin-left: 20px;" @click="removeDevice">删除设备</el-button> -->
  <el-row class="devices">
    <el-table ref="deviceListRef" :data="deviceSelected" fit @cell-click="handleClick">
      <el-table-column align="center" label="序号" type="index" width="80" />
      <el-table-column align="center" label="设备名称" prop="name"></el-table-column>
      <el-table-column align="center" label="设备编号" prop="code"></el-table-column>
      <!-- <el-table-column align="center" label-align="center" label="设备状态" prop="deviceStatusId"></el-table-column>
      <el-table-column align="center" label-align="center" label="使用状态" prop="useStatusId"></el-table-column> -->
      <el-table-column align="center" label="是否启用">
        <template #default="{ row }">
          <el-switch v-model="row.status" :active-value="`1`" :inactive-value="`0`" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注（点击新增或修改）" prop="remark">
      </el-table-column>
      <el-table-column label="操作" header-align="center">
        <template #default="{ row }">
          <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
            <el-button size="small" type="danger" @click="remove(row)">
              Delete
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>
  </el-row>

  <el-text tag="b" size="large">检查项目 </el-text>
  <!-- <el-button type="primary" size="small" style="margin-left: 50px;" @click="add">新增项目组</el-button> -->
  <!-- <el-button type="primary" size="small" style="margin-left: 50px;" @click="chooseProject"
    :disabled="addDisable">查询项目组</el-button> -->
  <el-select ref="projectChooseRef" v-model="basicInfo.projectId" size="small" placeholder="选择项目组" style="width: 140px"
    @change="chooseProject">
    <el-option v-for="(item, index) in projectList" :key="index" :label="item.name" :value="item.id"></el-option>
  </el-select>
  <el-row class="check">
    <el-table :data="checkList" fit>
      <el-table-column align="center" label="序号" type="index" width="80" />
      <el-table-column align="center" label="项目名称" prop="name"></el-table-column>
      <el-table-column align="center" label="项目内容" prop="content"></el-table-column>
      <el-table-column align="center" label="备注" prop="remark"></el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>
  </el-row>

  <el-drawer v-model="drawVisiable" title="设备列表" size="50%">
    <DeviceSelect :deptId="basicInfo.deptId" v-model:deviceSelected="deviceSelected"
      v-model:drawVisiable="drawVisiable">
    </DeviceSelect>
  </el-drawer>
  <el-dialog v-model="dialogVisiable" title="编辑备注">
    <el-input type="textarea" v-model="remark.remark"></el-input>
    <div style="width:100%; text-align: center;">
      <el-button type="primary" @click="remarkConfirm" style="width: 200px; margin-top: 20px;">确认</el-button>
    </div>
  </el-dialog>
  <div class="bottom">
    <el-button type="primary" @click="submitTactics">确认</el-button>
    <el-button class="cancel" @click="cancelTactics">取消</el-button>
  </div>
</template>

<style scoped lang="less">
.basicInfo,
.devices,
.check {
  padding: 20px 30px;
}

.el-select {
  width: 80px;
  height: 24px;
  padding: 0 11px;

  &.dept {
    width: 210px;
  }
}

.bottom {
  position: fixed;
  left: 50%;
  bottom: 30px;
  z-index: 200;

  .el-button {
    width: 100px;
  }

  .cancel {
    margin-left: 30px;
  }
}

:deep(.el-empty__image) {
  height: 100px;
}

:deep(th.el-table__cell) {
  background-color: var(--el-color-primary-light-7) !important;
}
</style>